package onez.project.core.helper;

import org.asynchttpclient.*;

import java.util.concurrent.CompletableFuture;


/**
 * 异步的http辅助类
 */
public class AsyncHttpHelper {

	private static final class SingletonHolder {
		private static final AsyncHttpHelper INSTANCE = new AsyncHttpHelper();
	}

	private AsyncHttpHelper() {

	}

	public static AsyncHttpHelper getInstance() {
		return SingletonHolder.INSTANCE;
	}

	private AsyncHttpClient asyncHttpClient;

    /**
     * 初始化异步HTTP客户端实例
     * @param asyncHttpClient 要使用的异步HTTP客户端实例，需在系统初始化时调用
     */
    public void initialized(AsyncHttpClient asyncHttpClient) {
        this.asyncHttpClient = asyncHttpClient;
    }
	/**
	 * 执行异步HTTP请求
	 * @param request 配置好的请求对象
	 * @return 包含响应结果的CompletableFuture，可通过它进行异步响应处理
	 */
	public CompletableFuture<Response> executeRequest(Request request) {
		ListenableFuture<Response> future = asyncHttpClient.executeRequest(request);
		return future.toCompletableFuture();
	}

	public <T> CompletableFuture<T> executeRequest(Request request, AsyncHandler<T> handler) {
		ListenableFuture<T> future = asyncHttpClient.executeRequest(request, handler);
		return future.toCompletableFuture();
	}

}
